package gnssio

import (
	"dgo/goutils/utils"
	"time"
)

type CommRawFileReWriter struct {
	filename    string
	IsUtcTime   bool
	FileNameFmt string //yyyy/$mm$/G06$dd$.E"
}

func NewRawFileReWriter(filefmt string) *CommRawFileReWriter {
	return &CommRawFileReWriter{
		IsUtcTime:   false,
		FileNameFmt: filefmt,
	}
}

// =================================================================
func (this *CommRawFileReWriter) Start() {
	_t := time.Now()
	if this.IsUtcTime {
		_t = _t.UTC()
	}
	if this.IsUtcTime {
		utils.Log.Debugf("输出文件(当前)(采用UTC时间):%s", this.currFile(_t))
	} else {
		utils.Log.Debugf("输出文件(当前)(采用本地时间):%s", this.currFile(_t))
	}

}

func (this *CommRawFileReWriter) Stop() {
}

func (this *CommRawFileReWriter) Send(buf []byte, len int) int {
	this.checkNewFile()
	this.tryWriteFile(buf[:len])
	return len
}

func (this *CommRawFileReWriter) AddListener(event I_CommListener) {
}

func (this *CommRawFileReWriter) RemoveListener(event I_CommListener) {
}

func (this *CommRawFileReWriter) currFile(_t time.Time) string {
	str := this.FileNameFmt
	str = utils.ParseTimeFmt(str, _t)
	return str
}

func (this *CommRawFileReWriter) checkNewFile() {
	_t := time.Now()
	if this.IsUtcTime {
		_t = _t.UTC()
	}
	str := this.currFile(_t)
	this.filename = str
}

func (this *CommRawFileReWriter) tryWriteFile(buf []byte) bool {
	err := utils.RewriteFile(this.filename, buf)
	if err != nil {
		utils.Log.Err(err)
		return false
	}
	return true
}
